<?php

namespace App\Models\Collection;

use App\Constant\ThirdMoneyCode;
use App\Exceptions\GeneralException;
use App\Library\Traits\RepaySmsRemind;
use App\ModelFilters\RepaySummaryFilter;
use App\Models\CollectionApiRequest;
use App\Models\Traits\PayCompensate;
use App\Models\Traits\Repay as RepayTrait;
use App\Models\UserBankCard;
use Carbon\Carbon;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use App\Models\Traits\RepaySummary as RepaySummaryTrait;
use App\Models\Traits\OldRepaySummary as OldRepaySummaryTrait;
use App\Models\Traits\RepaySummaryInteface;
use App\Models\Traits\RepayInfo as RepayInfoTrait;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * App\Models\RepaySummary
 *
 * @property int $id
 * @property int $uid 当前用户
 * @property int $loan_id 放款id
 * @property int $amount 总金额存分
 * @property int $period_count 总期数
 * @property int $period 当前的期数(0代表换不还清)
 * @property string $rate 后台配置,保存json
 * @property string 老卡贷放款id
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereLoanId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary wherePeriod($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary wherePeriodCount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereUpdatedAt($value)
 * @mixin \Eloquent
 * @property int $loan_request_id 授信申请表id
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\RepayRecord[] $recordMany
 * @property-read \App\Models\RepayRecord $recordOne
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary filter($input = array(), $filter = null)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary paginateFilter($perPage = null, $columns = array(), $pageName = 'page', $page = null)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary simplePaginateFilter($perPage = null, $columns = array(), $pageName = 'page', $page = null)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereBeginsWith($column, $value, $boolean = 'and')
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereEndsWith($column, $value, $boolean = 'and')
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereLike($column, $value, $boolean = 'and')
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereLoanRequestId($value)
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\RepayRecordCommon[] $common
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\RepayRecordMoney[] $money
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\RepayRecordMonth[] $month
 * @property int $status 状态(1 进行中 2 完成还款)
 * @property int $current_repay 当前用户的对应的当前还款
 * @property-read \App\Models\LoanApply $relationLoanApply
 * @property-read \App\Models\UserLoanRequest $relationUserLoanRequests
 * @property-read \App\Models\User $users
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereCurrentRepay($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereStatus($value)
 * @property int $data_type 新旧卡贷标识: 1: 新卡贷数据, 2:旧卡贷数据
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereDataType($value)
 */
class RepaySummary extends Model
{
    // 商户代偿（销账）功能 trait 包
    use PayCompensate;

    //current_repay 1当前记录, 0以前记录
    const CURRENT_REPAY_ZERO = 0;
    const CURRENT_REPAY_ONE = 1;

    //状态(1 进行中 2 完成还款)
    const STATUS_ONE = 1;
    const STATUS_TWO = 2;

    //资方接口和公共接口请求次数
    const MONEY_API_NUMBER = 10;
    const COMMON_API_NUMBER = 20;

    const MONEY_API = 'money';
    const COMMON_API = 'common';

    const FINES_RATE = 0.005;//农信罚息费率 默认千分之五

    //新旧卡贷标识: 1: 新卡贷数据, 2:旧卡贷数据
    const DATA_TYPE_ONE = 1;
    const DATA_TYPE_TWO = 2;

    //是否推送  0 未推送  1推送
    const UP_TYPE_ZERO = 0;
    const UP_TYPE_ONE = 1;

    //区分快闪卡贷版本0=>kskd-2,1:=>kskd,2=>kskd-1,3=>没数据的
    const KSKD_REPAY_TYPE_ZERO=0;
    const KSKD_REPAY_TYPE_ONE=1;
    const KSKD_REPAY_TYPE_TWO=2;
    const KSKD_REPAY_TYPE_THREE=3;


    //后台放款用户列表的赛选状态
    static $FULL_STATUS = [
        RepaySummary::STATUS_ONE => '还款中',
        RepaySummary::STATUS_TWO    => '还款完成',
    ];

    static $FULL_STATUS_DETAIL = [
        RepaySummary::STATUS_ONE => [
            RepayRecordMoney::TYPE_ONE           => '待还',
            RepayRecordMoney::TYPE_FIVE          => '逾期',
        ],
        RepaySummary::STATUS_TWO => [
            RepayRecordMoney::TYPE_TWO           => '逐期还款',
            RepayRecordMoney::TYPE_FOUR          => '余期还清',
        ],
    ];

    /**
     * 应该被转换成原生类型的属性。
     *
     * @var array
     */
    protected $casts = [
        'rate' => 'array',
    ];

    /**
     * 催收链接
     */
    protected $connection='backend';

    /**
     * 定义默认模型过滤器
     *
     * @return string
     */
    public function modelFilter()
    {
        return $this->provideFilter(RepaySummaryFilter::class);
    }


    /**
     * Description:和具体的期数一对多
     * Author:lijiafei
     */
    public function recordMany(){
        return $this->hasMany(RepayRecord::class,'summary_id','id')->orderBy('period','asc');
    }

    /**
     * Description:和具体的期数一对一
     * Author:lijiafei
     */
    public function recordOne(){
        //查询第一个不成功的记录
        return $this->hasOne(RepayRecord::class,'summary_id','id')->orderBy('period','asc');
    }

    /**
     * Description: relation一条记录
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function relationProcessingRecord() {
        return $this->hasOne(RepayRecord::class,'summary_id','id');
    }

    /**
     * Description: 关联资金记录表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function money()
    {
        return $this->hasMany('App\Models\Collection\RepayRecordMoney','summary_id','id');
    }

    /**
     * Description: 关联资金记录表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function month()
    {
        return $this->hasMany('App\Models\Collection\RepayRecordMonth','summary_id','id');
    }

    /**
     * Description: 关联公共记录表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function common()
    {
        return $this->hasMany('App\Models\Collection\RepayRecordCommon','summary_id','id');
    }

    /**
     * Description: 关联用户放款信息表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function relationLoanApply()
    {
        return $this->hasOne('App\Models\LoanApply', 'loan_request_id', 'loan_request_id');
    }

    /**
     * Description: 关联用户放款信息表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function relationUserLoanRequests()
    {
        return $this->hasOne('App\Models\UserLoanRequest', 'id', 'loan_request_id');
    }

    public function users(){
        return $this->belongsTo('App\Models\User','uid','id');
    }


    /**
     * Description: 设置资方记录利息费
     * Author: Gxs
     * @param $value
     */
    public function setAmountAttribute($value)
    {
        $this->attributes['amount'] = (int)bcmul($value, 100);
    }

    /**
     * Description: 获取资方记录利息费
     * Author: Gxs
     * @param $value
     * @return int
     */
    public function getAmountAttribute($value)
    {
        return bcdiv($value, 100, 2);
    }


    /**
     * 限制查询正在进行中的还款
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeDoing($query)
    {
        return $query->where('status', '=', self::STATUS_ONE);
    }









    public function verifyData(RepaySummary $summaryInfo){
        //判断是否有逾期的记录
        $day_number = count_days(Carbon::now()->toDateString(),$summaryInfo->recordOne->normal_date);
        if($day_number > 0){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当前还款记录有逾期记录,不能全部结清';
            return $returnData;
        }
        //判断当前银行卡是否有效
        $hold_agreement_num = UserBankCard::getHoldAgreementNumById($summaryInfo->recordOne->bank_cards_id,$summaryInfo->id);
        if(!$hold_agreement_num){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '用户的银行卡协议号有误';
            return $returnData;
        }
        if($summaryInfo === false){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '未查询到还款记录';
            return $returnData;
        }
        if($summaryInfo->recordOne->status == RepayRecord::STATUS_TWO){
            $returnData['status']=false;
            //代表这条记录还在轮询中,不要还款
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '正在还款中,不能全部结清';
            return $returnData;
        }
        //判断是否可以全部还清
        $isAllRepay = RepaySummary::isAllRepay($summaryInfo->recordOne);
        if(!$isAllRepay){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当前状态不能进行提前结清';
            return $returnData;
        }
        return ['result' => CollectionApiRequest::RESPONSE_OK];
    }







    /*
     * Description: 订单历史记录信息处理
     * Author: Gxs
     * @param RepaySummary $value
     * @return array
     */
    public static function parseHistoryInfo($value)
    {
        Log::debug('repay_history', ['value' => $value]);
        $pay_order_number = 0;
        if (!empty($value->relationLoanApply->trans_money_list)) {
            $pay_order_number = \App\Models\RepayRecord::getPayOrderNo($value->relationLoanApply->trans_money_list); //获取投保单号-_-
        }
        Log::debug('repay_history', [
            'value_id' => $value->id,
            'uid' => auth('api')->user()->getAuthIdentifier(),
        ]);
        $temp = [
            'id' => $value->id,
            'period_count' => $value->period_count, //总期数
            'loan_time' => Carbon::createFromTimeString($value->relationLoanApply->loan_time)->format('Y·m·d'), //借款日期
            'pay_order_number' => $pay_order_number, //获取投保单号-_-
            'amount' => $value->amount, //借款本金
        ];
        //获取当前次 最新期的 每期应还, 还款状态
        if (RepaySummary::STATUS_TWO == $value->status) {
            $current_where = [
                ['summary_id', '=', $value->id],
                ['period', '<>', 0],
            ];
            $current_order = 'desc';
        } else {
            $current_where = [
                ['summary_id', '=', $value->id],
                ['period', '<>', 0],
                ['status', '<>', RepayRecord::STATUS_FOUR],
            ];
            $current_order = 'asc';
        }
        $current_record = RepayRecord::where($current_where)->orderBy('normal_date', $current_order)->first();
        if (!empty($current_record)) {
            $lending_amount = bcadd($current_record->common->lending_money, $current_record->money->lending_money, 2); //总利息
            $manage_amount = bcadd($current_record->common->manage_money, $current_record->money->manage_money, 2); //总管理费
            $repay_amount = bcadd(bcadd(bcadd($lending_amount, $manage_amount, 2), $current_record->month->amount, 2), $current_record->amount, 2); //本期应还 = 实还金额
            $get_result_result = \App\Models\RepayRecord::getOtherMoneyAndType($value, $current_record);
            $type = $get_result_result['type'];
            $fines_amount = $get_result_result['fines_amount'];
            $pay_off_amount = $get_result_result['pay_off_amount'];
            $overdue_day = $get_result_result['overdue_day'];
            $repay_amount = bcadd(bcadd($fines_amount, $pay_off_amount, 2), $repay_amount, 2);
            $temp['period'] = $current_record->period; //当前期数
            $temp['type'] = $type;
            $temp['repay_amount'] = $repay_amount; //应还金额(包含罚息)
            $temp['fines_amount'] = $fines_amount;//罚息
            $temp['overdue_day'] = $overdue_day;//逾期天数
        } else {
            Log::debug('repay_history_index', ['message' => '未找到历史记录的最新期数据', 'current_where' => $current_where]);
            $temp['period'] = 1; //当前期数
            $temp['type'] = RepayRecord::RETURN_TYPE_ONE;
            $temp['repay_amount'] = '0.00';
            $temp['fines_amount'] = '0.00';
            $temp['overdue_day'] = 0;
        }
        return $temp;
    }

    /**
     * 是否全部还清
     * @author lvyinhong
     * @param $repaySummary
     * @return bool
     */
    public static function isPayOff($repaySummary)
    {
        if ($repaySummary instanceof self) {
           return intval($repaySummary->period) === 0;
        }
        return false;
    }



    /**
     * Description: 获取是否为晋商资方渠道
     * Author: Gxs
     * @param $summary_id
     * @return bool true 晋商, false 其他
     */
    public static function getLoanChannel($summary_id)
    {
        $summary_model = RepaySummary::find($summary_id);
        if(self::DATA_TYPE_ONE == $summary_model->data_type){
            return true;
        }
        if ('LCC201709190010' == $summary_model->loan_channel)
            return true; //晋商 || 新光大
        else
            return false;
    }



    /**
     * Description: 获取订单唯一标识 loan_id
     * Author:tianp
     * @param
     * @return string|mixed
     */
    public function getCaseCode()
    {
        return $this->loan_id;
    }




}